/* Copyright 2007 Gearbox Software - http://www.gearboxsoft.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
     http:www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.*/
using System;
using System.Collections.Generic;
using System.Text;

namespace GearBlog.UnitTests
{
	using System.Configuration;
	using Castle.ActiveRecord;
	using Castle.ActiveRecord.Framework;
	using GearBlog.Web.Models;

	public static class ActiveRecordService
	{
		private static bool init;
		private static User currentUser;
		private static Role currentRole;
		private static Setting currentSetting;


		public static User CurrentUser
		{
			get { return currentUser; }
		}

		public static Role CurrentRole
		{
			get { return currentRole; }
		}

		public static Setting CurrentSetting
		{
			get { return currentSetting; }
		}

		public static void Start()
		{
			if (!init)
			{
				IConfigurationSource source =
					ConfigurationManager.GetSection("activerecord") as IConfigurationSource;

				ActiveRecordStarter.Initialize(typeof (GearBlog.Web.Models.Post).Assembly, source);
			}
			
			ActiveRecordStarter.DropSchema();
			ActiveRecordStarter.CreateSchema();

			InitRole();

			InitUser();

			InitSettings();

			init = true;

		}
		public static void Stop()
		{
			ActiveRecordStarter.DropSchema();
			currentUser = null;
			currentRole = null;
			currentSetting = null;
		}
		private static void InitRole()
		{
			currentRole = new Role();
			currentRole.Name = "admin";
			currentRole.Save();
		}

		private static void InitUser()
		{
			currentUser = new User();
			currentUser.UserName = "admin";
			currentUser.FullName = "admin";
			currentUser.Password = "admin";
			currentUser.Email = "admin@admin.com";
			currentUser.SetPasswordHash();
			currentUser.Roles.Add(Role.FindByName("admin"));
			currentUser.Save();
		}

		private static void InitSettings()
		{
			currentSetting = new Setting();
			currentSetting.NumOfDaysBeforeArchive = 30;
			currentSetting.RegisteredUserOnly = false;
			currentSetting.RegisteredUserCommentOnly = false;
			currentSetting.Title = "Your Blog Title Here";
			currentSetting.Description = "Your Blog Description Here";
			currentSetting.OwnerEmail = currentUser.Email;
			currentSetting.AllowPublicRegistration = true;
			currentSetting.TrackBackTimeOut = 30;
			currentSetting.ModerateComments = false;
			currentSetting.Save();

		}
	}
}
